from users.models import EmailVerifyCode
from random import randrange
from django.core.mail import send_mail
from GuLiEdu.settings import EMAIL_FROM


def get_random_code(code_length):
    code_source = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
    code = ""
    for i in range(code_length):
        a = code_source[randrange(start=1, stop=len(code_source) - 1)]
        code += a
    return code


def send_email_code(email, send_type):
    # 第一步  创建邮箱验证码对象，保存数据库，用来以后做对比
    code = get_random_code(8)
    a = EmailVerifyCode()
    a.email = email
    a.send_type = send_type
    a.code = code
    a.save()
    # 第二步  发送邮件
    """
    send_mail(subject(发邮件的标题), message（邮件内容）, from_email（从哪发？）, recipient_list（给谁发？【是一个列表】）,
    其他都是默认值参数
              fail_silently=False, auth_user=None, auth_password=None,
              connection=None, html_message=None):
    """
    send_title = ""
    send_body = ""
    if send_type == 1:
        send_title = "欢迎注册"
        send_body = "请点击以下链接激活您的账号：\n http://127.0.0.1:8000/users/user_active/" + code
        send_mail(send_title, send_body, EMAIL_FROM, [email], )
    elif send_type == 2:
        send_title = "重置密码"
        send_body = "请点击以下链接重新设置您的密码：\n http://127.0.0.1:8000/users/user_reset/" + code
        send_mail(send_title, send_body, EMAIL_FROM, [email], )
    elif send_type == 3:
        send_title = "修改邮箱"
        send_body = "您的验证码是："+ code
        send_mail(send_title, send_body, EMAIL_FROM, [email], )
